import { storageSet, storageGet, storageRemove, isTauri, getTokenAsync } from './secure-storage';
import { API_BASE_URL } from '@/config/env';

// 标准化群组ID（确保以 group_ 开头，且只添加一次）
const normalizeGroupId = (group_id: string): string => {
  if (!group_id) return group_id;
  // 移除所有重复的 group_ 前缀
  let normalized = group_id.trim();
  while (normalized.startsWith('group_')) {
    normalized = normalized.substring(6); // 移除 'group_' (6个字符)
  }
  // 确保只有一个 group_ 前缀
  return `group_${normalized}`;
};

// 缓存键名（与好友、聊天记录隔离）
const GROUPS_CACHE_KEY = 'groups_cache';
const GROUPS_CACHE_TIMESTAMP_KEY = 'groups_cache_timestamp';
const GROUP_MEMBERS_CACHE_KEY_PREFIX = 'group_members_cache';

// 获取当前用户的 open_id（用于缓存键）
// 注意：前端统一使用 open_id 作为用户的唯一标识
const getCurrentUserId = (): string | null => {
  // 只使用 openId，不再使用 snowflakeId 或 userId
  return localStorage.getItem('openId');
};

// 异步获取当前用户的 open_id（用于 Tauri 环境，确保获取到最新的 open_id）
const getCurrentUserIdAsync = async (): Promise<string | null> => {
  if (isTauri()) {
    // Tauri 环境中，从安全存储获取 open_id
    try {
      const openId = await storageGet('openId');
      if (openId) return openId;
    } catch (e) {
      console.warn('从安全存储获取 open_id 失败，使用 localStorage:', e);
    }
  }
  // 回退到 localStorage
  return getCurrentUserId();
};

// 获取用户特定的缓存键
const getGroupsCacheKey = async (userId?: string | null): Promise<string> => {
  let uid = userId;
  if (!uid) {
    // 如果没有提供 userId，尝试获取当前用户ID
    if (isTauri()) {
      // Tauri 环境中，尝试异步获取
      uid = await getCurrentUserIdAsync();
    } else {
      uid = getCurrentUserId();
    }
  }
  return uid ? `${GROUPS_CACHE_KEY}_${uid}` : GROUPS_CACHE_KEY;
};

const getGroupsCacheTimestampKey = async (userId?: string | null): Promise<string> => {
  let uid = userId;
  if (!uid) {
    if (isTauri()) {
      uid = await getCurrentUserIdAsync();
    } else {
      uid = getCurrentUserId();
    }
  }
  return uid ? `${GROUPS_CACHE_TIMESTAMP_KEY}_${uid}` : GROUPS_CACHE_TIMESTAMP_KEY;
};

const getGroupMembersCacheKey = async (group_id: string, userId?: string | null): Promise<string> => {
  let uid = userId;
  if (!uid) {
    if (isTauri()) {
      uid = await getCurrentUserIdAsync();
    } else {
      uid = getCurrentUserId();
    }
  }
  return uid ? `${GROUP_MEMBERS_CACHE_KEY_PREFIX}_${group_id}_${uid}` : `${GROUP_MEMBERS_CACHE_KEY_PREFIX}_${group_id}`;
};

// 清除群组列表缓存（用于登录/登出时）
// 注意：只清除群组列表相关的缓存，不会影响好友和聊天记录
export const clearGroupsCache = async (userId?: string | null): Promise<void> => {
  try {
    const cacheKey = await getGroupsCacheKey(userId);
    const timestampKey = await getGroupsCacheTimestampKey(userId);
    
    // 只删除群组列表相关的键（groups_cache_* 和 groups_cache_timestamp_*）
    // 不会影响好友（friends_cache_*）和聊天记录（chat_messages_*）
    await storageRemove(cacheKey);
    await storageRemove(timestampKey);
  } catch (error) {
    console.error('清除群组列表缓存失败:', error);
  }
};

// 保存群组列表到缓存
export const saveGroupsToCache = async (groups: ImGroup[]): Promise<void> => {
  try {
    const cacheKey = await getGroupsCacheKey();
    const timestampKey = await getGroupsCacheTimestampKey();
    const userId = await getCurrentUserIdAsync();
    const data = JSON.stringify(groups);
    const timestamp = Date.now().toString();
    
    console.log('保存群组到缓存 - 用户ID:', userId, '缓存键:', cacheKey, '群组数量:', groups.length);
    console.log('群组列表详情:', groups.map(g => ({ id: g.group_id, name: g.group_name })));
    
    await storageSet(cacheKey, data);
    await storageSet(timestampKey, timestamp);
    console.log('群组列表已保存到缓存:', groups.length, '个群组', '缓存键:', cacheKey);
  } catch (error) {
    console.error('保存群组列表到缓存失败:', error);
  }
};

// 从缓存读取群组列表
export const loadGroupsFromCache = async (): Promise<ImGroup[] | null> => {
  try {
    const cacheKey = await getGroupsCacheKey();
    const cached = await storageGet(cacheKey);
    if (cached) {
      const groups = JSON.parse(cached) as ImGroup[];
      return groups;
    }
  } catch (error) {
    console.error('从缓存读取群组列表失败:', error);
  }
  return null;
};

// 更新缓存中的单个群组（用于增删改操作）
export const updateGroupInCache = async (
  action: 'add' | 'update' | 'remove',
  group?: ImGroup,
  group_id?: string
): Promise<void> => {
  try {
    const cached = await loadGroupsFromCache();
    if (!cached) return;

    let updated: ImGroup[];
    switch (action) {
      case 'add':
        if (group) {
          // 检查是否已存在
          const exists = cached.some(g => g.group_id === group.group_id);
          if (!exists) {
            updated = [...cached, group];
          } else {
            // 如果已存在，更新它
            updated = cached.map(g => g.group_id === group.group_id ? group : g);
          }
        } else {
          updated = cached;
        }
        break;
      case 'update':
        if (group) {
          updated = cached.map(g => g.group_id === group.group_id ? group : g);
        } else {
          updated = cached;
        }
        break;
      case 'remove':
        if (group_id) {
          updated = cached.filter(g => g.group_id !== group_id);
        } else {
          updated = cached;
        }
        break;
      default:
        updated = cached;
    }

    await saveGroupsToCache(updated);
  } catch (error) {
    console.error('更新群组缓存失败:', error);
  }
};

// 保存群组成员列表到缓存
export const saveGroupMembersToCache = async (group_id: string, members: ImGroupMember[]): Promise<void> => {
  try {
    const cacheKey = await getGroupMembersCacheKey(group_id);
    const data = JSON.stringify(members);
    await storageSet(cacheKey, data);
  } catch (error) {
    console.error('保存群组成员列表到缓存失败:', error);
  }
};

// 从缓存读取群组成员列表
export const loadGroupMembersFromCache = async (group_id: string): Promise<ImGroupMember[] | null> => {
  try {
    const cacheKey = await getGroupMembersCacheKey(group_id);
    const cached = await storageGet(cacheKey);
    if (cached) {
      const members = JSON.parse(cached) as ImGroupMember[];
      console.log('从缓存加载群组成员列表:', group_id, members.length, '个成员');
      return members;
    }
  } catch (error) {
    console.error('从缓存读取群组成员列表失败:', error);
  }
  return null;
};

// 更新缓存中的群组成员（用于增删改操作）
export const updateGroupMemberInCache = async (
  group_id: string,
  action: 'add' | 'update' | 'remove',
  member?: ImGroupMember,
  member_id?: string
): Promise<void> => {
  try {
    const cached = await loadGroupMembersFromCache(group_id);
    if (!cached) return;

    let updated: ImGroupMember[];
    switch (action) {
      case 'add':
        if (member) {
          // 检查是否已存在
          const exists = cached.some(m => m.member_id === member.member_id);
          if (!exists) {
            updated = [...cached, member];
          } else {
            // 如果已存在，更新它
            updated = cached.map(m => m.member_id === member.member_id ? member : m);
          }
        } else {
          updated = cached;
        }
        break;
      case 'update':
        if (member) {
          updated = cached.map(m => m.member_id === member.member_id ? member : m);
        } else {
          updated = cached;
        }
        break;
      case 'remove':
        if (member_id) {
          updated = cached.filter(m => m.member_id !== member_id);
        } else {
          updated = cached;
        }
        break;
      default:
        updated = cached;
    }

    await saveGroupMembersToCache(group_id, updated);
    console.log('群组成员缓存已更新:', group_id, action, member?.member_id || member_id);
  } catch (error) {
    console.error('更新群组成员缓存失败:', error);
  }
};

// 清除群组成员缓存
export const clearGroupMembersCache = async (group_id: string): Promise<void> => {
  try {
    const cacheKey = await getGroupMembersCacheKey(group_id);
    await storageRemove(cacheKey);
  } catch (error) {
    console.error('清除群组成员缓存失败:', error);
  }
};

export interface ImGroup {
  group_id: string;
  owner_id: string;
  group_type: number;
  group_name: string;
  mute?: number;
  apply_join_type: number;
  avatar?: string;
  max_member_count?: number;
  introduction?: string;
  notification?: string;
  status?: number;
  sequence?: number;
  create_time?: number;
  update_time?: number;
  extra?: string;
  version?: number;
  del_flag: number;
  verifier?: number;
  member_count?: number;
}

export interface ImGroupMember {
  group_member_id: string;
  group_id: string;
  member_id: string;
  role: number;
  speak_date?: number;
  mute: number;
  alias?: string;
  join_time?: number;
  leave_time?: number;
  join_type?: string;
  extra?: string;
  del_flag: number;
  create_time?: number;
  update_time?: number;
  version?: number;
}

export interface CreateGroupRequest {
  group_id: string;
  group_name: string;
  group_type: number;
  apply_join_type: number;
  avatar?: string;
  max_member_count?: number;
  introduction?: string;
  notification?: string;
  verifier?: number;
}

export interface AddGroupMemberRequest {
  member_id: string;
  role?: number;
  alias?: string;
}

// 从服务器获取群组列表
// onlyToday: 如果为 true，只返回当天的数据（用于缓存为空时的首次同步）
export const fetchGroupsFromServer = async (onlyToday: boolean = false): Promise<ImGroup[]> => {
  const token = await getTokenAsync();
  if (!token) {
    throw new Error('未登录，请先登录');
  }
  
  const response = await fetch(`${API_BASE_URL}/api/im/groups`, {
    headers: {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json',
    },
  });

  if (!response.ok) {
    const error = await response.json().catch(() => ({ message: '获取群组列表失败' }));
    throw new Error(error.message || '获取群组列表失败');
  }

  const data = await response.json();
  let groups = data.groups || [];
  
  // 如果只同步当天的数据，过滤掉历史很久的数据
  if (onlyToday) {
    const todayStart = new Date();
    todayStart.setHours(0, 0, 0, 0);
    const todayStartTimestamp = todayStart.getTime();
    
    groups = groups.filter((group: ImGroup) => {
      // 使用 update_time 或 create_time，取较大的值（表示最近的活动时间）
      const lastActiveTime = Math.max(
        group.update_time || 0,
        group.create_time || 0
      );
      // 只保留今天的数据
      return lastActiveTime >= todayStartTimestamp;
    });
    
    console.log('只同步当天的群组数据，过滤后数量:', groups.length);
  }
  
  // 保存到缓存
  await saveGroupsToCache(groups);
  
  return groups;
};

export const createGroup = async (req: CreateGroupRequest): Promise<void> => {
  const token = await getTokenAsync();
  if (!token) {
    throw new Error('未登录，请先登录');
  }
  const response = await fetch(`${API_BASE_URL}/api/im/groups`, {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(req),
  });

  if (!response.ok) {
    const error = await response.json().catch(() => ({ message: '创建群组失败' }));
    throw new Error(error.message || '创建群组失败');
  }

  // 创建成功后，重新从服务器获取最新列表并更新缓存
  await fetchGroupsFromServer();
};

export const getUserGroups = async (useCache: boolean = true): Promise<{ groups: ImGroup[] }> => {
  // 如果使用缓存，先尝试从缓存读取
  if (useCache) {
    const cached = await loadGroupsFromCache();
    if (cached && cached.length > 0) {
      // 异步从后端更新（不阻塞）
      fetchGroupsFromServer().catch(err => {
        console.error('后台更新群组列表失败:', err);
      });
      return { groups: cached };
    }
  }

  // 缓存为空时，只同步当天的数据（避免同步历史很久的数据）
  const groups = await fetchGroupsFromServer(true);
  return { groups };
};

export const getGroup = async (group_id: string): Promise<ImGroup> => {
  const token = await getTokenAsync();
  if (!token) {
    throw new Error('未登录，请先登录');
  }
  // 标准化群组ID（确保以 group_ 开头）
  const normalizedGroupId = normalizeGroupId(group_id);
  const response = await fetch(`${API_BASE_URL}/api/im/groups/${encodeURIComponent(normalizedGroupId)}`, {
    headers: {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json',
    },
  });

  if (!response.ok) {
    const error = await response.json().catch(() => ({ message: '获取群组失败' }));
    const errorMessage = error.message || '获取群组失败';
    // 如果是404错误，使用更明确的错误消息
    if (response.status === 404) {
      throw new Error(`群组不存在: ${group_id}`);
    }
    throw new Error(errorMessage);
  }

  return response.json();
};

// 从服务器获取群组成员列表
const fetchGroupMembersFromServer = async (group_id: string): Promise<ImGroupMember[]> => {
  const token = await getTokenAsync();
  if (!token) {
    throw new Error('未登录，请先登录');
  }
  // 标准化群组ID（确保以 group_ 开头）
  const normalizedGroupId = normalizeGroupId(group_id);
  const response = await fetch(`${API_BASE_URL}/api/im/groups/${encodeURIComponent(normalizedGroupId)}/members`, {
    headers: {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json',
    },
  });

  if (!response.ok) {
    const error = await response.json().catch(() => ({ message: '获取群成员失败' }));
    throw new Error(error.message || '获取群成员失败');
  }

  const data = await response.json();
  const members = data.members || [];
  
  // 保存到缓存
  await saveGroupMembersToCache(group_id, members);
  
  return members;
};

export const getGroupMembers = async (group_id: string, useCache: boolean = true): Promise<ImGroupMember[]> => {
  // 如果使用缓存，先尝试从缓存读取
  if (useCache) {
    const cached = await loadGroupMembersFromCache(group_id);
    if (cached && cached.length > 0) {
      // 异步从后端更新（不阻塞）
      fetchGroupMembersFromServer(group_id).catch(err => {
        console.error('后台更新群组成员列表失败:', err);
      });
      return cached;
    }
  }

  // 从后端获取最新数据
  return await fetchGroupMembersFromServer(group_id);
};

export const addGroupMember = async (group_id: string, req: AddGroupMemberRequest): Promise<string> => {
  const token = await getTokenAsync();
  if (!token) {
    throw new Error('未登录，请先登录');
  }
  
  // 标准化群组ID（确保以 group_ 开头）
  const normalizedGroupId = normalizeGroupId(group_id);
  
  // 先更新本地缓存（乐观更新）
  const now = Date.now();
  const member: ImGroupMember = {
    group_member_id: `${normalizedGroupId}_${req.member_id}`,
    group_id: normalizedGroupId,
    member_id: req.member_id,
    role: req.role || 0,
    mute: 1,
    alias: req.alias,
    join_time: now,
    del_flag: 1,
    create_time: now,
    update_time: now,
    version: 1,
  };
  await updateGroupMemberInCache(normalizedGroupId, 'add', member);
  
  const response = await fetch(
    `${API_BASE_URL}/api/im/groups/${encodeURIComponent(normalizedGroupId)}/members/${encodeURIComponent(req.member_id)}`,
    {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(req),
    }
  );

  if (!response.ok) {
    // 如果后端添加失败，重新从服务器获取最新列表并更新缓存
    await fetchGroupMembersFromServer(normalizedGroupId);
    const error = await response.json().catch(() => ({ message: '添加群成员失败' }));
    throw new Error(error.message || '添加群成员失败');
  }
  
  // 解析响应，获取返回的group_id（如果从2人升级到3人，后端会返回新的唯一group_id）
  const result = await response.json().catch(() => ({}));
  const finalGroupId = result.group_id ? normalizeGroupId(result.group_id) : normalizedGroupId;
  
  // 如果group_id改变了，需要更新缓存中的group_id
  if (finalGroupId !== normalizedGroupId) {
    // TODO: 更新本地缓存中的group_id，包括消息缓存等
  }
  
  // 添加成功后，重新从服务器获取最新列表并更新缓存（确保数据一致性）
  await fetchGroupMembersFromServer(finalGroupId);
  
  // 返回最终的group_id
  return finalGroupId;
};

export const removeGroupMember = async (group_id: string, member_id: string): Promise<void> => {
  const token = await getTokenAsync();
  if (!token) {
    throw new Error('未登录，请先登录');
  }
  
  // 标准化群组ID（确保以 group_ 开头）
  const normalizedGroupId = normalizeGroupId(group_id);
  
  // 先更新本地缓存（乐观更新）
  await updateGroupMemberInCache(normalizedGroupId, 'remove', undefined, member_id);
  
  const response = await fetch(
    `${API_BASE_URL}/api/im/groups/${encodeURIComponent(normalizedGroupId)}/members/${encodeURIComponent(member_id)}`,
    {
      method: 'DELETE',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json',
      },
    }
  );

  if (!response.ok) {
    // 如果后端删除失败，重新从服务器获取最新列表并更新缓存
    await fetchGroupMembersFromServer(normalizedGroupId);
    const error = await response.json().catch(() => ({ message: '移除群成员失败' }));
    throw new Error(error.message || '移除群成员失败');
  }
  
  // 删除成功后，重新从服务器获取最新列表并更新缓存（确保数据一致性）
  await fetchGroupMembersFromServer(normalizedGroupId);
};

export const updateMemberRole = async (group_id: string, member_id: string, role: number): Promise<void> => {
  const token = await getTokenAsync();
  if (!token) {
    throw new Error('未登录，请先登录');
  }
  
  // 标准化群组ID（确保以 group_ 开头）
  const normalizedGroupId = normalizeGroupId(group_id);
  
  // 先更新本地缓存（乐观更新）
  const cached = await loadGroupMembersFromCache(normalizedGroupId);
  if (cached) {
    const member = cached.find(m => m.member_id === member_id);
    if (member) {
      const updatedMember = { ...member, role, update_time: Date.now() };
      await updateGroupMemberInCache(normalizedGroupId, 'update', updatedMember);
    }
  }
  
  const response = await fetch(
    `${API_BASE_URL}/api/im/groups/${encodeURIComponent(normalizedGroupId)}/members/${encodeURIComponent(member_id)}/role`,
    {
      method: 'PUT',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ role }),
    }
  );

  if (!response.ok) {
    // 如果后端更新失败，重新从服务器获取最新列表并更新缓存
    await fetchGroupMembersFromServer(normalizedGroupId);
    const error = await response.json().catch(() => ({ message: '更新成员角色失败' }));
    throw new Error(error.message || '更新成员角色失败');
  }
  
  // 更新成功后，重新从服务器获取最新列表并更新缓存（确保数据一致性）
  await fetchGroupMembersFromServer(normalizedGroupId);
};

// 更新群成员别名（我在本群的昵称）
export const updateMemberAlias = async (group_id: string, member_id: string, alias: string | null): Promise<void> => {
  const token = await getTokenAsync();
  if (!token) {
    throw new Error('未登录，请先登录');
  }
  
  // 标准化群组ID（确保以 group_ 开头）
  const normalizedGroupId = normalizeGroupId(group_id);
  
  // 先更新本地缓存（乐观更新）
  const cached = await loadGroupMembersFromCache(normalizedGroupId);
  if (cached) {
    const member = cached.find(m => m.member_id === member_id);
    if (member) {
      const updatedMember = { ...member, alias: alias || undefined, update_time: Date.now() };
      await updateGroupMemberInCache(normalizedGroupId, 'update', updatedMember);
    }
  }
  
  const response = await fetch(
    `${API_BASE_URL}/api/im/groups/${encodeURIComponent(normalizedGroupId)}/members/${encodeURIComponent(member_id)}/alias`,
    {
      method: 'PUT',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ alias: alias || null }),
    }
  );

  if (!response.ok) {
    // 如果后端更新失败，重新从服务器获取最新列表并更新缓存
    await fetchGroupMembersFromServer(normalizedGroupId);
    const error = await response.json().catch(() => ({ message: '更新群昵称失败' }));
    throw new Error(error.message || '更新群昵称失败');
  }
  
  // 更新成功后，重新从服务器获取最新列表并更新缓存（确保数据一致性）
  await fetchGroupMembersFromServer(normalizedGroupId);
};

export const deleteGroup = async (group_id: string): Promise<void> => {
  const token = await getTokenAsync();
  if (!token) {
    throw new Error('未登录，请先登录');
  }
  
  // 标准化群组ID（确保以 group_ 开头）
  const normalizedGroupId = normalizeGroupId(group_id);
  
  // 先更新本地缓存（乐观更新）
  await updateGroupInCache('remove', undefined, normalizedGroupId);
  await clearGroupMembersCache(normalizedGroupId);
  
  const response = await fetch(
    `${API_BASE_URL}/api/im/groups/${encodeURIComponent(normalizedGroupId)}/delete`,
    {
      method: 'DELETE',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json',
      },
    }
  );

  if (!response.ok) {
    // 如果后端删除失败，重新从服务器获取最新列表并更新缓存
    await fetchGroupsFromServer();
    const error = await response.json().catch(() => ({ message: '删除群组失败' }));
    throw new Error(error.message || '删除群组失败');
  }
  
  // 删除成功后，重新从服务器获取最新列表并更新缓存（确保数据一致性）
  await fetchGroupsFromServer();
};

export const dissolveGroup = async (group_id: string): Promise<void> => {
  const token = await getTokenAsync();
  if (!token) {
    throw new Error('未登录，请先登录');
  }
  
  // 标准化群组ID（确保以 group_ 开头）
  const normalizedGroupId = normalizeGroupId(group_id);
  
  // 先更新本地缓存（乐观更新）
  await updateGroupInCache('remove', undefined, normalizedGroupId);
  await clearGroupMembersCache(normalizedGroupId);
  
  try {
    const response = await fetch(
      `${API_BASE_URL}/api/im/groups/${encodeURIComponent(normalizedGroupId)}/dissolve`,
      {
        method: 'DELETE',
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json',
        },
      }
    );

    if (!response.ok) {
      // 如果后端解散失败，重新从服务器获取最新列表并更新缓存
      await fetchGroupsFromServer();
      const error = await response.json().catch(() => ({ 
        message: response.status === 400 ? '只有群主才能解散群组' : '解散群组失败',
        code: response.status
      }));
      const errorMessage = error.message || (response.status === 400 ? '只有群主才能解散群组' : '解散群组失败');
      throw new Error(errorMessage);
    }
  } catch (error: any) {
    // 处理网络错误
    if (error.name === 'TypeError' && error.message.includes('Failed to fetch')) {
      throw new Error('无法连接到服务器，请检查服务器是否运行');
    }
    // 重新抛出其他错误
    throw error;
  }
  
  // 解散成功后，重新从服务器获取最新列表并更新缓存（确保数据一致性）
  await fetchGroupsFromServer();
};

export interface UpdateGroupRequest {
  group_name?: string;
  introduction?: string;
  avatar?: string;
  notification?: string;
  apply_join_type?: number;
  max_member_count?: number;
}

export const updateGroup = async (group_id: string, req: UpdateGroupRequest): Promise<void> => {
  const token = await getTokenAsync();
  if (!token) {
    throw new Error('未登录，请先登录');
  }
  
  // 标准化群组ID（确保以 group_ 开头）
  const normalizedGroupId = normalizeGroupId(group_id);
  
  // 先更新本地缓存（乐观更新）
  const cached = await loadGroupsFromCache();
  if (cached) {
    // 尝试用原始ID和标准化ID查找
    const group = cached.find(g => g.group_id === group_id || g.group_id === normalizedGroupId);
    if (group) {
      const updatedGroup = { ...group, ...req, update_time: Date.now() };
      await updateGroupInCache('update', updatedGroup);
    }
  }
  
  const response = await fetch(`${API_BASE_URL}/api/im/groups/${encodeURIComponent(normalizedGroupId)}`, {
    method: 'PUT',
    headers: {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(req),
  });

  if (!response.ok) {
    // 如果后端更新失败，检查是否是群组不存在的情况
    const error = await response.json().catch(() => ({ message: '更新群组信息失败' }));
    const errorMessage = error.message || '更新群组信息失败';
    const errorCode = error.code || '';
    
    // 如果是群组不存在（404或NotFound错误码或消息），从缓存中移除该群组
    const isNotFound = response.status === 404 || 
                       errorCode === 'NOT_FOUND' || 
                       errorCode === 'NotFound' ||
                       errorMessage.includes('不存在') || 
                       errorMessage.includes('NotFound');
    
    if (isNotFound) {
      console.warn(`群组不存在，从缓存中移除: ${normalizedGroupId} (原始ID: ${group_id})`);
      // 同时尝试移除原始ID和标准化ID
      await updateGroupInCache('remove', undefined, group_id);
      await updateGroupInCache('remove', undefined, normalizedGroupId);
      throw new Error('群组不存在，可能已被删除');
    }
    
    // 如果后端更新失败，重新从服务器获取最新列表并更新缓存
    await fetchGroupsFromServer();
    throw new Error(errorMessage);
  }
  
  // 更新成功后，重新从服务器获取最新列表并更新缓存（确保数据一致性）
  await fetchGroupsFromServer();
};

export const transferGroupOwner = async (group_id: string, new_owner_id: string): Promise<void> => {
  const token = await getTokenAsync();
  if (!token) {
    throw new Error('未登录，请先登录');
  }
  
  // 标准化群组ID（确保以 group_ 开头）
  const normalizedGroupId = normalizeGroupId(group_id);
  
  const response = await fetch(
    `${API_BASE_URL}/api/im/groups/${encodeURIComponent(normalizedGroupId)}/transfer-owner`,
    {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ new_owner_id }),
    }
  );

  if (!response.ok) {
    const error = await response.json().catch(() => ({ message: '转让群主失败' }));
    throw new Error(error.message || '转让群主失败');
  }
  
  // 转让成功后，重新从服务器获取最新列表并更新缓存（确保数据一致性）
  await fetchGroupsFromServer();
  await fetchGroupMembersFromServer(group_id);
};

